/*
 * @(#)MD5.java
 *
 * Copyright (c) 2015 DHC Corporation.
 */
package com.dhc.appbusinessfrm.util;

import java.security.MessageDigest;


public class MD5 {

	/**
	 * Byte数组MD5加密
	 * 
	 * @param bytes
	 *            需要加密的Byte数组
	 * @return 加密后的Byte数组
	 */
	public static byte[] getMd5(byte[] bytes) {
		try {
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(bytes);
			return algorithm.digest();
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 字符串MD5加密
	 * 
	 * @param str
	 *            需要加密的字符串
	 * @return 加密后的字符串
	 */
	public static String getMd5(String str) {
		try {
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(str.getBytes("utf-8"));
			String md5 = new String(algorithm.digest(), "utf-8");
			return md5;
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 字符串MD5加密
	 * 
	 * @param str
	 *            需要加密的字符串
	 * @return 加密后的Byte数组
	 */
	public static byte[] getMd5b(String str) {
		try {
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(str.getBytes("utf-8"));
			return algorithm.digest();
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 字符串MD5加密
	 * 
	 * @param str
	 *            需要加密的字符串
	 * @return 加密后的字符串
	 */
	public static String getMD5Str(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		// 将加密后的byte数组转换为十六进制的字符串,否则的话生成的字符串会乱码
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			} else {
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		}

		return md5StrBuff.toString();
	}
}
